package cn.ibizlab.core.authentication.service.impl;

import cn.hutool.json.JSONObject;
import cn.ibizlab.core.authentication.domain.SMSResponse;
import cn.ibizlab.core.authentication.service.SMSService;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;

/**
 * sms4j短信服务
 */
@Service
@ConditionalOnExpression("'${ibiz.auth.sms.service:sms4j}'.equals('sms4j')")
public class SMS4JSMSService implements SMSService {

    @Value("${sms.supplier:alibaba}")
    private String supplier;

    /**
     * 发送短信
     * @param phone
     * @param message
     * @return
     */
    @Override
    public SMSResponse sendMessage(String phone, String message) {
        SmsResponse response = SmsFactory.getBySupplier(supplier).sendMessage(phone, message);
        SMSResponse result = sendMessageResult(response);
        return result;
    }

    /**
     * 指定模板发送短信
     * @param phone
     * @param templateId
     * @param messages
     * @return
     */
    @Override
    public SMSResponse sendMessage(String phone, String templateId, LinkedHashMap<String, String> messages) {
        SmsResponse response = SmsFactory.getBySupplier(supplier).sendMessage(phone, templateId, messages);
        SMSResponse result = sendMessageResult(response);
        return result;
    }

    public SMSResponse sendMessageResult(SmsResponse response) {
        SMSResponse result = new SMSResponse();
        if (response.getData() != null && response.getData() instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) response.getData();
            result.setMessage(jsonObject.getStr("msg"));
            result.setCode(jsonObject.getStr("code"));
            result.setDetail(response.getData());
            result.setSuccess(response.isSuccess());
        }
        return result;
    }

}
